package api

import (
	"cap/global"
	"fmt"
	"github.com/gin-gonic/gin"
	"lib/middleware"
	"path/filepath"
)

func StartHttpServer(apiPrefix string) (err error) {
	app := gin.New()
	staticGroup := app.Group(fmt.Sprintf("%s/static/", apiPrefix))
	staticRouter(staticGroup) // 静态资源组

	aipGroup := app.Group(apiPrefix)
	aipGroup.Use(middleware.HttpLog())
	adminGroup(aipGroup)
	guaGroup(aipGroup)
	clientGroup(aipGroup)
	err = app.Run(global.Conf.Http.Addr)
	return err
}

func staticRouter(r *gin.RouterGroup) {
	r.Static("/pic", filepath.Join(global.Conf.AppFolder, "pic"))
}

func adminGroup(r *gin.RouterGroup) {
	sub := r.Group("")
	sub.Use(middleware.GinAuthorizationMiddleAware())
	// 主机
	sub.POST("host/add", HostApi.AddHost)
	sub.GET("host/page", HostApi.PageHost)
	sub.DELETE("host/del", HostApi.DelHost)
	// 集群
	sub.POST("cluster/add", HostApi.AddCluster)
	sub.POST("cluster/edit", HostApi.EditCluster)
	sub.GET("cluster/list", HostApi.FindClusterList)
	sub.GET("cluster/dtoList", HostApi.FindClusterDtoList)
	sub.DELETE("cluster/del", HostApi.DelCluster)
	// 链接
	sub.POST("link/add", HostApi.LinkBindUser)
	sub.GET("link/list", HostApi.LinkList)
	sub.GET("link/detail/:id", HostApi.LinkDetail)

	// 会话
	sub.POST("session/add", SessionApi.Create)
	sub.GET("session/page", SessionApi.Page)
	sub.POST("session/appInfo", SessionApi.GetCapAppInfo)
	sub.POST("session/openApp", SessionApi.InsertOpenAppLogs)  // 写入应用的打开日志
	sub.POST("session/bindWinId", SessionApi.BindWinSessionId) // 绑定 win id

	//凭证
	sub.GET("certify/list", HostApi.GetCertifyList)
	sub.GET("certify/page", HostApi.CertifyPage)
	sub.DELETE("certify/del", HostApi.DelCertify)
	sub.POST("certify/add", HostApi.AddCertify)

	// cap 专用功能，包括：创建win账户、删除win账户、映射盘符、挂盘等。也就是调用客户端插件
	// cap应用
	sub.GET("app/list", HostApi.AppList)
	sub.POST("app/issue", HostApi.AppIssue)
	sub.POST("host/bindCluster", HostApi.BindCluster)          // 绑定集群
	sub.POST("notice/appUpload", HostApi.NoticeHostUploadApps) // 通知主机上报应用信息
	sub.POST("notice/register", HostApi.NoticeHostRegister)    // 通知主机重新注册
	//
}

// cap_client 上报数据
func clientGroup(r *gin.RouterGroup) {
	sub := r.Group("client")

	sub.POST("register", ClientApi.Register)
	sub.POST("uploadCloudApp", ClientApi.UploadCloudApp)
	sub.POST("winSessionChange", ClientApi.NoticeWinSessionChange)
}

func guaGroup(r *gin.RouterGroup) {
	sub := r.Group("")
	// sub.Use(middleware.GinAuthorizationMiddleAware()) // ws 不能使用这个中间件，而且也不能使用 http.GetCurrentUser(c) 方法
	sub.GET("session/conn", SessionApi.Conn)
}
